package com.ruoyi.common.utils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {

    public static String PRIVATE_KEY_PEM = "-----BEGIN RSA PRIVATE KEY-----\n" +
        "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCmHV3cXa5Pv6n0\n" +
        "aQo9InLPlcKZ3TWRXrb3Qdv+vaUl7Dl8Mr7Cq+9UA1JQkhALMAql2spTin2rvelL\n" +
        "Gy+lK7K/heOxlaw49v878NgOoeFx+Ik0mq0ccp7eFsVOsbEwMpvSPIoUC9UzDZ3m\n" +
        "fx5z14gz7KGCPZ51cXiUseRgksp94OW2bDRZU68mkyCgeCI/5st3u+rT+QBve3DZ\n" +
        "kpeT4h08i61O2suw/7Xim95cQ9KGCG+nivNq1Q42rYFP1A36Zp7JyxxR1nlSKKsl\n" +
        "hSSINNgmgW9Tc2VxFOZiIaBU2WBplETANi+nSBVuPiKx1cO1k3GkWCs5ukgjcLQ0\n" +
        "CTRsGj/JAgMBAAECggEBAJ/D7tpbX6Nj+9oOjMJvt2zf5OKHV1YRengk56oCTCxF\n" +
        "HqTNSZuCMhTjfO/xC203L4aE/8OJl4TuisqpwxFhDfIWm//YrGO9a44C/kpUd7he\n" +
        "CdiGS6jotNN1ox8k1/47LpLtlv/gwZTwq8VczbUsvtrx5ASXryfVktuwnK4lgIu/\n" +
        "iNbAC52itJoOVz1tlBosL3K7own2jk18xVi1/Kp+Dv/rmiGftMkdpqpuepI7DYln\n" +
        "J606cCAy/jFA8AbG40EdyCk8Nx/uCESYXtwhaewFt7G0CV9MqCYbNFAIQFs14XuY\n" +
        "cEcpTX7qFphAL4waj+tV+ggA5c8XOigg3wtu9/XFxOECgYEA8GTXyuCP2mt1mdDU\n" +
        "RymTssJv6rfB7HPw4CK95HwGrOhfATg/baSZnwG10cR81vTCr8ywgf2V7ETEVaxz\n" +
        "3yNI/gJ7jmU1VGHLMdy+74Hz87uLy5twFq1Hlo3HjfQpcrziYSXoFo3wwOT6nypt\n" +
        "bZlmItq2RUXF+TAv5Yg+2NYo5yMCgYEAsOYP3q2BYH1eolk4wgE8incQMVgwF2C1\n" +
        "BSQmp1RQC2LZnaQRMBHY8o2BNTydr+B3rzOULML6lQt8MGIShSuGNnh4ATg3UaLv\n" +
        "eepzVFL3m+Y3hQiI4dekAWHNDrEs+AiKVM31xHU6hTs5aOap8+Wh5dDmCqsWjJ8e\n" +
        "22w2ebfwIiMCgYA1pxwukI4qvp8htGUceOAZHqJh7Z9ficTyEW72ZuQKhVZm7Enj\n" +
        "y7/pqDUPW15Nj5VALVwbtyBV+kcjo/i8jaCF6MHw1w/fBHCYcV9AD24GMQ6TY97R\n" +
        "gN0gcgZe3Wa+z/9qlU5GcmmQc8qn6Y1Az+Lm1o+lyFvWMPYPsaftN2crpwKBgAlv\n" +
        "C3OdnyOtK+nOhkdaV4cu2E85W78zahPvHJyZ03b3+5D7mesNWJt+zmAvbl1dxCQ0\n" +
        "xPcqIsDmDuZppIEzlAG9pPCztceFv+2pgiMCFbBbs6RFkz8wB9AHDi91ZWeI1Q+2\n" +
        "uB+U/Nz0Dpi4jGG0YlDmNg5ll1tCdRvQhosxMv4vAoGBAONhqfqVXuq7XDRatqX7\n" +
        "eAAZCGPMBpOmMMBhxjOjjJDpY9W0E9Xy0Cka5zr8p7DwbQ9Li1F+d/xurwTEFtyh\n" +
        "Kk4Lv+2matJjd+mE+4i3YfeGPcLrVuConfEP6Vo+pYeSpyoSgmBLK1db/CyvK6wF\n" +
        "4cCwUM5XQHK/skvE8tIyUbu1\n" +
        "-----END RSA PRIVATE KEY-----";

    /**
     * RSA 解密（直接从PEM字符串解密）
     *
     * @param encryptedData Base64编码的加密数据
     * @return 解密后的原始字符串
     * @throws Exception 解密异常
     */
    public static String decryptFromPem(String encryptedData) throws Exception {
        PrivateKey privateKey = loadPrivateKeyFromPem(PRIVATE_KEY_PEM);
        return decrypt(encryptedData, privateKey);
    }


    /**
     * 从 PEM 格式字符串加载私钥
     *
     * @param privateKeyPem PEM格式的私钥字符串
     * @return PrivateKey 对象
     * @throws Exception 密钥加载异常
     */
    public static PrivateKey loadPrivateKeyFromPem(String privateKeyPem) throws Exception {
        try {
            String privateKeyContent = privateKeyPem
                .replace("-----BEGIN RSA PRIVATE KEY-----", "")
                .replace("-----END RSA PRIVATE KEY-----", "")
                .replaceAll("\\s", "");

            byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyContent);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            throw new Exception("加载RSA私钥失败", e);
        }
    }

    /**
     * RSA 解密
     *
     * @param encryptedData Base64编码的加密数据
     * @param privateKey    私钥
     * @return 解密后的原始字符串
     * @throws Exception 解密异常
     */
    public static String decrypt(String encryptedData, PrivateKey privateKey) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            throw new Exception("RSA解密失败", e);
        }
    }


}
